package com.zw.pdm.module.designtask.service;

import com.zw.pdm.entity.basic.Dept;
import com.zw.pdm.entity.com.ComTaskName;
import com.zw.pdm.entity.com.DsnTaskCommon;
import com.zw.pdm.entity.designtask.DsnMakeChangeQuery;
import com.zw.pdm.module.designtask.mapper.DesignTaskMapper;
import com.zw.pdm.module.designtask.mapper.DsnTaskChangeMapper;
import com.zw.pdm.module.designtask.repository.DsnMakeChangeQueryRepository;
import com.zw.pdm.module.designtask.repository.DsnTaskCommonRepository;
import com.zw.pdm.module.report.model.Project;
import com.zw.pdm.module.system.repository.DeptRepository;
import com.zw.pdm.util.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Author: China.wsg
 * @Date: 2020/11/13 16:35
 */
@Service
@SuppressWarnings("all")
public class DsnTaskChangeService {

    @Autowired
    private DsnTaskChangeMapper dsnTaskChangeMapper;
    @Autowired
    private DesignTaskAddService designTaskAddService;
    @Autowired
    private DeptRepository deptRepository;
    @Autowired
    private DesignTaskMapper designTaskMapper;
    @Autowired
    private DsnTaskCommonRepository taskRepository;
    @Autowired
    private DsnMakeChangeQueryRepository dsnMakeChangeQueryRepository;
    @Autowired
    private DsnProcessService dsnProcessService;
    @Value("${saleUrl}")
    private String saleUrl;

    /**
     * 按照条件取项目信息
     *
     * @param project
     * @return
     */
    public List<Project> findProjectByQuery(Project project) {
        return dsnTaskChangeMapper.findProjectByQuery(project);
    }

    /**
     * 按照项目ID取得任务科室
     *
     * @param project
     * @return
     */
    public List<Dept> findTaskDeptsByProId(Integer proId) {
        return dsnTaskChangeMapper.findTaskDeptsByProId(proId);
    }

    /**
     * 保存任务变更
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean saveChange(Integer proId,String comment, Integer[] oldId, Integer[] newId, Integer[] editFlg) {
        //保存变更记录
        Project project = designTaskMapper.findProjectById(proId);
        int n = saveChangeMakeQuery(project, oldId, newId, editFlg, comment);
        List<Integer> sectionList = new ArrayList<>();
        for (int i = 0; i < editFlg.length; i++) {

            if (editFlg[i] == 2) {
                // 新增科室（集合取得）
                sectionList.add(newId[i]);
            } else if (newId[i] == null && oldId[i] != null) {
                // 取消科室
                dsnTaskChangeMapper.delTaskCommonByProIdAndDeptId(proId, oldId[i]);
            } else if (newId[i] != null && oldId[i] != null && newId[i] != oldId[i]) {
                // 修改科室
                dsnTaskChangeMapper.changeTaskCommonByProIdAndDeptId(proId, oldId[i], newId[i]);
            }
        }

        // 新增科室
        if (sectionList.size() > 0) {
            DsnTaskCommon comTask;
            for (Integer id : sectionList) {
                Dept dept = deptRepository.getOne(id);
                // 取得设计所有任务类型
                List<ComTaskName> taskNames = designTaskMapper.findTaskNameByDict("'设计科室任务'");
                for (ComTaskName taskName : taskNames) {
                    comTask = new DsnTaskCommon();
                    comTask.setDeptId(id);
                    comTask.setProId(proId);
                    comTask.setProCode(project.getCode());
                    comTask.setProName(project.getName());
                    comTask.setComTaskNameId(taskName.getId());
                    comTask.setComTaskName(taskName.getName());

                    String sepcial = dsnProcessService.findDeptInfoByAccount(id);
                    Integer specialId = 0;
                    if (sepcial.equals("机械")) {
                        specialId = 60;
                    } else if (sepcial.equals("流体")) {
                        specialId = 61;
                    } else if (sepcial.equals("自动化")) {
                        specialId = 62;
                    }
                    comTask.setSpecialId(specialId);
                    comTask.setSpecial(sepcial);
                    taskRepository.save(comTask);
                }
            }
        }

        // update by wsg 20211021 原因：bug修复，更改科室的同时，要更新dsn_pro_common.depts字段
        String deptNames = dsnTaskChangeMapper.getDeptNamesByProId(proId);
        dsnTaskChangeMapper.updateDsnProCommonDeptsByProId(proId,deptNames);

        // 跨域修改项目备注
        if (comment.compareTo(project.getComment()) != 0) {
            boolean boolFlg = updateProComment(saleUrl + "/projectScheduling/updateProComment", project.getCode(), comment);
            if (!boolFlg) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return false;
            }
        }
        return true;
    }

    /**
     * 跨域修改 项目备注
     *
     * @param saleUrl   接口地址
     * @param proCode   项目编号
     * @param comment 项目备注
     * @return
     */
    private boolean updateProComment(String saleUrl, String proCode, String comment) {
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> bodyMap = new LinkedMultiValueMap<>();
        bodyMap.add("proCode", proCode);
        bodyMap.add("comment", comment);
        return restTemplate.postForObject(saleUrl, bodyMap, Boolean.class);
    }

    /**
     * 保存变更记录
     *
     * @param proId
     * @param oldId
     * @param newId
     * @param editFlg
     * @return
     */
    private int saveChangeMakeQuery(Project project, Integer[] oldId, Integer[] newId, Integer[] editFlg, String comment) {
        String changeValue = "";
        for (int i = 0; i < editFlg.length; i++) {
            if (editFlg[i] == 2) {
                // 新增科室（集合取得）
                if(changeValue!=""){
                    changeValue+="<br>";
                }
                changeValue += "新增：【" + deptRepository.getOne(newId[i]).getName()+"】";
            } else if (newId[i] == null && oldId[i] != null) {
                // 取消科室
                if(changeValue!=""){
                    changeValue+="<br>";
                }
                changeValue += "取消：【" + deptRepository.getOne(oldId[i]).getName()+"】";
            } else if (newId[i] != null && oldId[i] != null && newId[i] != oldId[i]) {
                // 修改科室
                if(changeValue!=""){
                    changeValue+="<br>";
                }
                changeValue += "修改：【" +deptRepository.getOne(oldId[i]).getName()+"】 -> 【"+ deptRepository.getOne(newId[i]).getName()+"】";
            }
        }
        // 项目备注修改
        if (comment.compareTo(project.getComment()) != 0){
            if(changeValue!=""){
                changeValue+="<br>";
            }
            changeValue += "备注：【" +project.getComment()+"】 -> 【"+ comment+"】";
        }
        if (changeValue==""){
            return  2;
        }
        DsnMakeChangeQuery dsnMakeChangeQuery = new DsnMakeChangeQuery();
        dsnMakeChangeQuery.setProCode(project.getCode());
        dsnMakeChangeQuery.setProId(project.getId());
        dsnMakeChangeQuery.setChangeTime(new Date());
        dsnMakeChangeQuery.setChangeUser(ShiroUtils.getUser().getName());
        dsnMakeChangeQuery.setChangeUserCode(ShiroUtils.getUser().getAccount());
        dsnMakeChangeQuery.setChangeValue(changeValue);
        dsnMakeChangeQuery.setIsDel(0);
        dsnMakeChangeQuery.setProName(project.getName());
        dsnMakeChangeQuery.setProNum(project.getNum());
        dsnMakeChangeQueryRepository.save(dsnMakeChangeQuery);
        return 1;
    }

}
